﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;

namespace DNA.Mvc
{
    [Table("dna_messages")]
    public class PrivateMessage : SimpleMessage
    {
        public PrivateMessage() 
        {
            Received = DateTime.UtcNow;
            Sent = DateTime.UtcNow;
            ContentType = "text/html";
        }

        public PrivateMessage(IMessage message)
        {
            this.Title = message.Title;
            this.Content = message.Content;
            this.ContentType = message.ContentType;
            this.Encoding = message.Encoding;
            this.Sender = "System";
        }

        public PrivateMessage(string from, string to, string title, string content,string contentType="text/html"):this()
        {
            this.Sender = from;
            this.Receivers = to;
            this.Title = title;
            this.ContentType = content;
            this.ContentType = contentType;
        }

        [Key]
        [Column("ID", Order = 1)]
        public int ID { get; set; }
       
        [StringLength(1024)]
        public string Sender { get; set; }
        
        [Column(TypeName="ntext")]
        public string Receivers { get; set; }

        [Column(TypeName = "ntext")]
        public string Reads { get; set; }

        public DateTime Received { get; set; }

        public DateTime Sent { get; set; }

        public bool IsRead(string userName)
        {
            return GetReceivers().Contains(userName);
        }

        public void Read(string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                var receivers = GetReceivers();
                if (receivers.Contains(userName))
                {
                    if (!IsRead(userName))
                    {
                        receivers.ToList().Add(userName);
                        Receivers = string.Join(",", receivers);
                    }
                }
            }
        }

        public string[] GetReceivers() 
        {
            if (!string.IsNullOrEmpty(Receivers)) 
                return Receivers.Split(',');
            return new string[]{};
        }

        public string UserName { get; set; }
    }
}
